const deviceModel = require('../model/device');
const channelModel = require('../model/channel');
const constants = require('../data/constants');
const log4js      = require('../data/log');
const logger      = log4js.getLogger('sip');

module.exports = {
	/**
	 * 从数据库加载设备缓存信息,如果没加载到返回空
	 * @param {*} deviceid 设备号
	 */
	loadDevice: function (deviceid) {
		return new Promise(async function (resolve, reject) {
			if (!constants.sip.option) {
				logger.error('sipSetting 设置错误');
				reject('sipSetting 参数错误,deviceId=' + deviceid);
			} else {
				if (!constants.registry[deviceid] || !constants.registry[deviceid].channels) {
					// 从数据库加载
					let deviceInfoInDb = await deviceModel.getDeviceByDeviceId(deviceid);

					if(deviceInfoInDb) {
						// 取channel列表
						const channelList = await channelModel.list(deviceid);
						deviceInfoInDb.channels={};
						channelList.map((item)=>{
							deviceInfoInDb.channels[item.deviceid] = deviceModel.generateEmptyChannel(deviceInfoInDb, item.deviceid);
						})
						// logger.info(`从数据库加载的 ${deviceid} 设备信息+channels:`, deviceInfoInDb,'数据库里channels', channelList);
						constants.registry[deviceid] = Object.assign({
							deviceid, session: {
								realm: constants.sip.option.server_realm
							}
						}, deviceInfoInDb);
						// constants.registry[deviceid] = {
						// 	online: deviceInfoInDb.online, deviceid,
						// 	session: {
						// 		realm: constants.sip.option.server_realm
						// 	},
						// 	password: deviceInfoInDb.password,
						// 	sumnum: deviceInfoInDb.sumnum,
						// 	version: deviceInfoInDb.version,
						// 	device_type: deviceInfoInDb.device_type,
						// 	device_name: deviceInfoInDb.device_name,
						// 	server_id: deviceInfoInDb.server_id,
						// 	rtsp_url: deviceInfoInDb.rtsp_url,
						// 	protocol: deviceInfoInDb.protocol,
						// 	sip_command_host: deviceInfoInDb.sip_command_host,
						// 	sip_command_port: deviceInfoInDb.sip_command_port,
						// 	channels: [] //list
						// };
					}

				}
				// 对 host 修复,类似 sip_command_host: '::ffff:112.22.222.222',
				// constants.registry[deviceid].sip_command_host = constants.registry[deviceid].sip_command_host.replace("::ffff:","");

				resolve(constants.registry[deviceid]);
			}
		});
	}
};
